# coding:utf-8

"""
Win32Util.py
"""

import traceback
import win32gui
import os
import signal

from time import sleep
from win32con import CF_TEXT, CF_DIB, SW_RESTORE, KEYEVENTF_KEYUP, WM_CLOSE
from win32clipboard  import OpenClipboard, EmptyClipboard, SetClipboardData, CloseClipboard
from win32api import SetCursorPos, mouse_event, keybd_event, ShellExecute
from PIL import Image  
from cStringIO import StringIO
import win32pdh

ALT_KEY = 0x12
CTRL_KEY = 0x11
C_KEY = 0x43
V_KEY = 0x56
S_KEY = 0x53


def getPid(processName):
	#each instance is a process, you can have multiple processes w/same name
	junk, instances = win32pdh.EnumObjectItems(None,None,'process', win32pdh.PERF_DETAIL_WIZARD)
	proc_dict={}
	for instance in instances:
		if instance in proc_dict:
			proc_dict[instance] = proc_dict[instance] + 1
		else:
			proc_dict[instance]=0
	for instance, max_instances in proc_dict.items():
		if instance == processName:
		# for inum in xrange(max_instances+1):
			hq = win32pdh.OpenQuery() # initializes the query handle 
			path = win32pdh.MakeCounterPath( (None,'process',instance, None, max_instances,'ID Process') )
			counter_handle=win32pdh.AddCounter(hq, path) 
			win32pdh.CollectQueryData(hq) #collects data for the counter 
			types, val = win32pdh.GetFormattedCounterValue(counter_handle, win32pdh.PDH_FMT_LONG)
			win32pdh.CloseQuery(hq) 
			return val
	else:
		return 0


def killProcess(pid):
	"""杀死进程"""
	try:
		a = os.kill(pid, signal.SIGINT)
		print 'Kill process pid: %s, return: %s...' % (pid, a)
	except OSError as e:
		print e

def closeWindow(hwnd):
	"""关闭窗口"""
	win32gui.PostMessage(hwnd, WM_CLOSE, 0, 0)
	print 'Close window...'

def getWindowText(hwnd):
	"""获取窗口进程描述"""
	return win32gui.GetWindowText(hwnd)


def openLnkFile(lnkFilePath):
	ShellExecute(0, 'open', lnkFilePath, '','',1)

def setClipboard(data, types='image'):  
	"""写入剪切板"""  
	OpenClipboard()  
	try:  
		# Unicode tests  
		EmptyClipboard() 
		if types == 'image': 
			SetClipboardData(CF_DIB, data)
		elif types == "text":
			SetClipboardData(CF_TEXT, data)  
	except:  
		traceback.print_exc()  
	finally:  
		CloseClipboard()  

def readImage(imageFileName):
	"""读图片文件"""
	img = Image.open(imageFileName)  
	output = StringIO()  
	img.convert("RGB").save(output, "BMP")  
	data = output.getvalue()[14:]  
	output.close()
	return data

def getWindowHandle(title):
	return win32gui.FindWindow(None, unicode(title, 'utf-8'))

def setForegroundWindow(handle):
	"""窗口最前"""
	win32gui.ShowWindow(handle, SW_RESTORE)
	win32gui.SetActiveWindow(handle)  
	win32gui.SetForegroundWindow(handle)

def getWindowRect(handle):
	"""获取窗口坐标"""
	return win32gui.GetWindowRect(handle)

def setCursorPos(x, y):
	"""设置鼠标位置"""
	SetCursorPos((x, y))

def clickMouseLeft():
	"""单机鼠标左键"""
	mouse_event(0x0002, 0, 0, 0, 0) 
	mouse_event(0x0004, 0, 0, 0, 0)

def doubleKey(key1=0x12, key2=0x53):
	"""组合键"""
	keybd_event(key1,0,0,0)                  # ALT
	keybd_event(key2,0,0,0)                  # S
	keybd_event(key2,0,KEYEVENTF_KEYUP,0)
	keybd_event(key1,0,KEYEVENTF_KEYUP,0)

def toGbkText(text):
	if isinstance(text, unicode):
		return text.encode('gbk')
	else:
		try:
			return unicode(text, 'utf-8').encode('gbk')
		except:
			return text

def toUtf8Text(text):
	if isinstance(text, unicode):
		return text.encode('utf-8')
	else:
		try:
			return unicode(text, 'gbk').encode('utf-8')
		except:
			return text

def getFiles(dirPath):
	for root, dirs, files in os.walk(dirPath):
		return files
	else:
		return []

if __name__ == '__main__':
	print getFiles('qq_groups')



# coding:utf-8
from win32gui import GetWindowText, EnumWindows, PostMessage
from win32con import WM_CLOSE
import win32process

import os
import signal

WINDOW_TEXT = "微信"

def killProcess(pid):
	"""杀死进程"""
	try:
		a = os.kill(pid, signal.SIGINT)
		print 'Kill process pid: %s, return: %s...' % (pid, a)
	except OSError as e:
		print e

def closeWindow(hwnd):
	"""关闭窗口"""
	PostMessage(hwnd, WM_CLOSE, 0, 0)
	print 'Close window...'

def getWindowText(hwnd):
	"""获取窗口进程描述"""
	return GetWindowText(hwnd)

def closeCQ(hwnd, mouse):
	"""处理函数_关闭酷Q程序"""
	if getWindowText(hwnd) == unicode(WINDOW_TEXT, 'utf-8').encode('gbk'):
		closeWindow(hwnd)
		pids = win32process.GetWindowThreadProcessId(hwnd)
		print pids
		killProcess(pids[1])

if __name__ == '__main__':
	EnumWindows(closeCQ, 0)